import time

from django.http import HttpResponse
from django.shortcuts import render, redirect
from app01 import models
from alipay import AliPay, DCAliPay, ISVAliPay
import os
from alipay_demo import settings
from app01.models import Order


def index(request):
    goods_list = models.Goods.objects.all()
    return render(request,'index.html',{'goods_list':goods_list})


# 根据APPID和支付宝网关以及公钥和私钥，生成要跳转到的支付宝的支付页面
app_private_key_string = open(os.path.join(settings.BASE_DIR, 'keys/app_private_key.pem')).read()
alipay_public_key_string = open(os.path.join(settings.BASE_DIR, 'keys/alipay_public_key.pem')).read()

def buy(request,*args,**kwargs):
    goods_id = kwargs.get('goods_id')
    goods_obj = models.Goods.objects.filter(id=goods_id).first()
    no = time.time()
    # 生成订单
    models.Order.objects.create(
        # 订单id
        no = str(no),
        # 商品id
        goods_id = goods_obj.id
    )

    alipay = AliPay(
        appid=settings.APPID,
        app_notify_url=settings.APP_NOTIFY_URL,  # 回调url,post,这个url必须是公网ip
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True,  # 默认False，默认不加dev（正式环境）
    )

    # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
    order_string = alipay.api_alipay_trade_page_pay(
        subject=goods_obj.name,
        out_trade_no=no,
        total_amount=goods_obj.price,
        return_url=settings.RETURN_URL,
    )
    pay_url = 'https://openapi.alipaydev.com/gateway.do?'+order_string
    return redirect(pay_url)


def check_order(request):
    """支付宝来post这个回调接口，通知支付情况，让我们修改订单状态"""
    if request.method == 'POST':
        # 创建用于进行支付宝支付的工具对象
        alipay = AliPay(
            appid=settings.APPID,
            app_notify_url=settings.APP_NOTIFY_URL,  # 回调url,post,这个url必须是公网ip
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True  # 默认False，默认不加dev（正式环境）
        )
        from urllib.parse import parse_qs
        # 因为是post所以会在body中传参
        body_str = request.body.decode('utf8')
        # 根据&分割
        post_data = parse_qs(body_str)
        post_dict = {}
        for k,v in post_data.items():
            post_dict[k] = v
        sign = post_dict.pop('sign',None)
        status = alipay.verify(post_dict,sign)
        if status:
            # TODO:支付成功，获取订单号，将订单状态更新
            # print(post_dict)
            out_trade_no = post_dict.get('out_trade_no')
            order_obj = Order.objects.filter(no=out_trade_no)
            order_obj.status = 2
            order_obj.save()
            return HttpResponse('success')
        else:
            return HttpResponse('支付失败')
    return HttpResponse("仅支持POST请求")


def show(request):
    """从支付宝跳回我们自己的网站"""
    if request.method == "GET":
        alipay = AliPay(
            appid=settings.APPID,
            app_notify_url=settings.APP_NOTIFY_URL,  # 回调url,post,这个url必须是公网ip
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True  # 默认False，默认不加dev（正式环境）
        )
        params = request.GET.dict()
        sign = params.pop('sign',None)
        status = alipay.verify(params,sign)
        if status:
            return HttpResponse("支付成功")
        else:
            return HttpResponse("支付失败")


    return HttpResponse("仅支持GET请求")